package first.endtoend.parse

import first.endtoend.Beneficiary
import first.endtoend.Level
import first.endtoend.Locality
import grails.validation.ValidationException
import org.springframework.transaction.annotation.Transactional


/*
@author : A.Olfa
 */

@Transactional
class ParseCSVLocalityService
{

    def Beneficiary beneficiaryInstance

    def parseLocalities(String filepath, boolean header)
    {
        println("####################### JE PASSE DANS PARSE LOCALITY #############")
        println("####################### PATH = " + filepath + " #############")
        def parse = new File(filepath).readLines()[1..-1]
        println("####################### APRES FILE #######################")

        def token = ';'
        for (line in parse)
        {
            // create a levelInstance and specify its properties
            Locality localityInstance
            Locality parentLocality
            Level levelInstance
            line.splitEachLine(token) { fields ->
                if (!fields[2].equals("null"))
                {
                    levelInstance = Level.findById(Float.parseFloat(fields[2]))

                }

                if (!fields[1].equals("null"))
                {
                    parentLocality = Locality.findById(Float.parseFloat(fields[1]))

                    localityInstance = new Locality(name: fields[0], localityParent: parentLocality, level: levelInstance)

                } else
                {
                    localityInstance = new Locality(name: fields[0], localityParent: null, level: levelInstance)

                }

                if (!localityInstance.validate())
                {
                    throw new ValidationException("Locality is not valid", localityInstance.errors)
                }

                localityInstance.save()
                if (localityInstance.hasErrors())
                    println localityInstance.errors


                parentLocality = new Locality()
            }

        }
        println("####################### SORTIT PARSE LOCALITY #######################")
    }
}